package com.dftdla.server.handler;

import com.dftdla.dao.mapper.UserGroupMapper;
import com.dftdla.dao.pojo.ChatGroupMsg;
import com.dftdla.dao.service.ChatGroupMsgService;
import com.dftdla.dao.service.ChatGroupService;
import com.dftdla.mq.publisher.RabbitMqPublisher;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.message.request.GroupChatRequestMessage;
import com.dftdla.util.Code;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {

    @Resource
    private UserGroupMapper userGroupMapper;
    @Resource
    private RabbitMqPublisher publish;
    @Resource
    private ChatGroupMsgService chatGroupMsgService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        msg.setFrom(msg.getUserId());
        List<Long> ids = userGroupMapper.getGroupMembers(msg.getGroupId());
        ChatGroupMsg chatGroupMsg = new ChatGroupMsg(msg);
        chatGroupMsgService.save(chatGroupMsg);
        publish.sendMsg(ids,chatGroupMsg);
        ctx.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS,chatGroupMsg).toString()));
        log.info("群聊msg:{},已提交发送",chatGroupMsg);
    }
}
